package util

import (
	"io/ioutil"
	"os"
	"path"
	"strings"
)

func RemoveAllNoContractFiles(contractPath string) error {
	deleted, err := WalkAllNoContractFiles(contractPath)
	if err != nil {
		return err
	}
	for _, del := range deleted {
		log.Debugf("RemoveAllNoContractFiles path: %s , deleted %s", contractPath, del)
		removeErr := os.RemoveAll(del)
		if removeErr != nil {
			log.Errorf("RemoveAllNoContractFiles %s failed %s", del, removeErr.Error())
		}
	}
	return nil
}

// 遍历contractPath下所有的go文件,检查是否含有protoGo和shim
func WalkAllNoContractFiles(contractPath string) ([]string, error) {
	var err error
	var fds []os.FileInfo
	var retArrays []string
	if _, err = os.Stat(contractPath); err != nil {
		return retArrays, err
	}
	if fds, err = ioutil.ReadDir(contractPath); err != nil {
		return retArrays, err
	}
	for _, fd := range fds {
		srcFilePath := path.Join(contractPath, fd.Name())
		if fd.IsDir() {
			subA, subErr := WalkAllNoContractFiles(srcFilePath)
			if subErr != nil {
				return retArrays, subErr
			}
			retArrays = append(retArrays, subA...)
		} else {
			isContractFile := checkFileIsContractFile(srcFilePath)

			if !isContractFile {
				retArrays = append(retArrays, srcFilePath)
			}
		}
	}
	return retArrays, nil
}

func checkFileIsContractFile(srcFilePath string) bool {
	return strings.HasSuffix(srcFilePath, ".go") ||
		strings.HasSuffix(srcFilePath, "go.mod") ||
		strings.HasSuffix(srcFilePath, "go.sum")
}
